package com.itzdm.ai.controller;


import com.itzdm.ai.config.AppConfig;
import com.itzdm.ai.config.JwtConfig;
import com.itzdm.ai.model.ChatMessage;
import com.itzdm.ai.service.ChatContextService;
import com.itzdm.ai.service.DashScopeService;
import com.itzdm.ai.util.JwtUtil;
import com.itzdm.common.context.UserContext;
import com.itzdm.common.result.Result;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;

/**
 * 聊天控制器
 */
@Slf4j
@RestController
public class ChatController {

    @Autowired
    private DashScopeService dashScopeService;

    @Autowired
    private ChatContextService chatContextService;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private JwtConfig jwtConfig;


    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(
            @RequestParam("content") String content,
            @RequestParam("token") String token
    ) {
        // 首先解析JWT token
        Claims claims = JwtUtil.parseJWT(jwtConfig.getSecretKey(), token);
        Long userId = Long.valueOf(claims.get("id").toString());

        // 拿到userId说明token合法,接着判断content是否为空
        if (content == null || content.trim().isEmpty()) {
            SseEmitter emitter = new SseEmitter();
            try {
                emitter.send(SseEmitter.event().name("error").data("消息内容不能为空"));
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
            return emitter;
        }

        // 创建SseEmitter，并设置超时时间
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时

        // 添加完成回调
        emitter.onCompletion(() -> {
            log.info("SSE连接完成");
        });

        // 添加超时回调
        emitter.onTimeout(() -> {
            log.info("SSE连接超时");
            try {
                emitter.complete();
            } catch (Exception e) {
                log.error("完成SSE连接时出错", e);
            }
        });

        // 添加错误回调
        emitter.onError((ex) -> {
            log.error("SSE连接错误", ex);
            try {
                emitter.complete();
            } catch (Exception e) {
                log.error("完成SSE连接时出错", e);
            }
        });

        // 异步处理流式响应
        dashScopeService.streamChat(userId, content, emitter);

        return emitter;
    }

    /**
     * 获取用户的消息历史
     */
    @GetMapping("/history")
    public Result<List<ChatMessage>> getHistory() {
        Long userId = UserContext.getUser();
        List<ChatMessage> history = chatContextService.getMessageHistory(userId);
        return Result.success(history);
    }

    /**
     * 清除用户的消息历史
     */
    @DeleteMapping("/history")
    public Result<Map<String, Object>> clearHistory() {
        Long userId = UserContext.getUser();
        chatContextService.clearChatContext(userId);
        return Result.success(Map.of("success", true, "message", "消息历史已清除"));
    }

    /**
     * 获取系统默认消息配置
     */
    @GetMapping("/system-message")
    public Result<Map<String, Object>> getSystemMessage() {
        String defaultSystemMessage = appConfig.getDefaultSystemMessage();
        return Result.success(Map.of(
                "success", true,
                "systemMessage", defaultSystemMessage != null ? defaultSystemMessage : ""
        ));
    }

    /**
     * 初始化/恢复用户的系统默认消息
     */
    @PostMapping("/init-system")
    public Result<Map<String, Object>> initSystemMessage() {
        Long userId = UserContext.getUser();
        String defaultSystemMessage = appConfig.getDefaultSystemMessage();
        if (defaultSystemMessage == null || defaultSystemMessage.trim().isEmpty()) {
            return Result.error("未配置默认系统消息");
        }

        chatContextService.setSystemMessage(userId, defaultSystemMessage);
        return Result.success(Map.of(
                "success", true,
                "message", "已初始化系统消息",
                "systemMessage", defaultSystemMessage
        ));
    }

}